/**
 * 换绑记录
 */

angular.module('inspinia', ['infinity.angular-chosen']).controller('terChangeBindCtrl',function($scope,$http,$state,$timeout,$stateParams,$compile,$filter,i18nService,SweetAlert,$document){
	i18nService.setCurrentLang('zh-cn');  //设置语言为中文
	//数据源
    $scope.changeStatusList=[{text:"全部",value:""},{text:"换绑成功",value:"1"},{text:"换绑失败",value:"2"}];
    $scope.changeStatusStr=[{text:"换绑成功",value:"1"},{text:"换绑失败",value:"2"},{text:"换绑失败",value:"3"},{text:"换绑失败",value:"4"}];
    $scope.synBindStatusList=[{text:"全部",value:""},{text:"是",value:"1"},{text:"否",value:"0"}]
    $scope.initInfo={merchantNo:"",changeStatus:"",synBindStatus:""};
    $scope.queryInfo=angular.copy($scope.initInfo);
	//查询
	$scope.selectInfo=function(){
		if($scope.loadImg){
			return;
		}

        $scope.submitting = true;
        $scope.loadImg = true;
        $http({
            url:"merTerChangeBind/selectMerTerChangeBindPage?pageNo=" + $scope.paginationOptions.pageNo +  "&pageSize=" + $scope.paginationOptions.pageSize,
            method:"post",
            data:$scope.queryInfo
        }).success(function (result) {
            $scope.submitting = false;
            $scope.loadImg = false;
            if (!result || !result.status){
                $scope.notice (result.msg);
                return;
            }
            $scope.gridOptions.data = result.data.page.result;
            $scope.gridOptions.totalItems = result.data.page.totalCount;
        })
	}
	//清空
    $scope.clear = function () {
        $scope.queryInfo=angular.copy($scope.initInfo);
    }

	$scope.gridOptions={                           //配置表格
		paginationPageSize:10,                  //分页数量
		paginationPageSizes: [10, 20,50,100],	  //切换每页记录数
		useExternalPagination: true,
		enableHorizontalScrollbar: 1,        //横向滚动条
		enableVerticalScrollbar : 1,  		//纵向滚动条
		columnDefs:[                           //表格数据
            { field: 'merchantName',displayName:'商户名称' ,width:150},
            { field: 'merchantNo',displayName:'商户编号',width:150},
            { field: 'oldSn',displayName:'原机具sn号',width:150},
            { field: 'newSn',displayName:'新机具sn号',width:150},
            { field: 'changeStatus',displayName:'换绑状态',width:150 ,cellFilter:"formatDropping:"+angular.toJson($scope.changeStatusStr)},
            { field: 'remark',displayName:'备注',width:150 },
            { field: 'agentName',displayName:'所属代理商名称',width:150 },
            { field: 'agentNo',displayName:'所属代理商编号',width:150 },
            { field: 'oneLevelAgentName',displayName:'一级代理商名称',width:150 },
            { field: 'oneLevelAgent',displayName:'一级代理商编号',width:150 },
            { field: 'operAgentName',displayName:'操作代理商名称',width:150 },
            { field: 'operAgent',displayName:'操作代理商编号',width:150 },
            { field: 'createTime',displayName:'换绑日期',width:150,cellFilter:'date:"yyyy-MM-dd HH:mm:ss"' },
            { field: 'action',displayName:'操作',width:150 ,pinnedRight:true, cellTemplate:
                '<div class="lh30">'+
                '<a ng-show="row.entity.changeStatus==2" ng-click="grid.appScope.upperBind(row.entity)">上游绑定</a> ' +
                 '</div>'
            }
		],
		onRegisterApi: function(gridApi) {
			$scope.gridApi = gridApi;
			gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
				$scope.paginationOptions.pageNo = newPage;
				$scope.paginationOptions.pageSize = pageSize;
				$scope.selectInfo();
			});
		}
	};


    //上游绑定
    $scope.upperBind=function (entity) {
        var str="确认进行上游绑定?";


        SweetAlert.swal({
                title:str,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnConfirm: true,
                closeOnCancel: true },
            function (isConfirm) {
                if (isConfirm) {
                    $http.post("merTerChangeBind/toUpperBind/"+entity.id,
                        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
                        .success(function(data){
                            if(data.status){
                                entity.changeStatus=4;
                                $scope.notice(data.msg);
                                $scope.query();
                            }else{
                                $scope.notice(data.msg);
                            }
                        })
                        .error(function(data){
                            $scope.notice(data.msg);
                        });
                }
            });
    };


    //-----商户名称/编号 下拉框查询 start -----//
    $scope.merchantSelectList = [];
    $scope.merchantSelectBase = [];
    //获取少量的商户
    $http.post("merchantBusinessProduct/getMerchantFew",
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
        .success(function(msg){
            //响应成功
            for(var i=0; i<msg.length; i++){
                $scope.merchantSelectList.push({value:msg[i].merchantNo,text:msg[i].merchantNo+"("+msg[i].merchantName+")"});
            }
            $scope.merchantSelectBase = angular.copy($scope.merchantSelectList);
        });

    $scope.getMerchantSelect =getMerchantSelect;
    var oldValueMer="";
    var timeoutMer="";
    function getMerchantSelect(value) {
        $scope.agenttMer = [];
        var newValueMer=value;
        if(newValueMer != oldValueMer){
            if (timeoutMer) $timeout.cancel(timeoutMer);
            timeoutMer = $timeout(
                function(){
                    $http.post('merchantBusinessProduct/getMerchantFew','item='+value,
                        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
                        .success(function (msg) {
                            for(var i=0; i<msg.length; i++){
                                $scope.agenttMer.push({value:msg[i].merchantNo,text:msg[i].merchantNo+"("+msg[i].merchantName+")"});
                            }
                            if($scope.agenttMer.length>0){
                                $scope.merchantSelectList = $scope.agenttMer;
                            }else{
                                $scope.merchantSelectList=$scope.merchantSelectBase;
                            }
                            oldValueMer = value;
                        });
                },800);
        }
    }
    //-----商户名称/编号 下拉框查询 end -----//



    //获取代理商
    $http.post("agentInfo/selectAllInfo")
        .success(function(msg){
            //响应成功
            for(var i=0; i<msg.length; i++){
                $scope.agent.push({value:msg[i].agentNo,text:msg[i].agentNo + " " + msg[i].agentName});
                $scope.oneAgent.push({value:msg[i].agentNo,text:msg[i].agentNo + " " + msg[i].agentName});
            }
        });
    //条件查询代理商
    $scope.agent=[];
    $scope.getStates =getStates;
    var oldValue="";
    var timeout="";
    function getStates(value) {
        $scope.agentt = [];
        var newValue=value;
        if(newValue != oldValue){
            if (timeout) $timeout.cancel(timeout);
            timeout = $timeout(
                function(){
                    $http.post('agentInfo/selectAllInfo','item=' + value,
                        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
                        .then(function (response) {
                            if(response.data.length==0) {
                                //$scope.agentt.push({value: "", text: "全部"});
                            }else{
                               // $scope.agentt.push({value: "", text: "全部"});
                                for(var i=0; i<response.data.length; i++){
                                    $scope.agentt.push({value:response.data[i].agentNo,text:response.data[i].agentNo + " " + response.data[i].agentName});
                                }
                            }
                            $scope.agent = $scope.agentt;
                            oldValue = value;
                        });
                },800);
        }
    };


    //条件查询一级代理商
    $scope.oneAgent=[];
    $scope.getStatesOne =getStatesOne;
    var oldValueOne="";
    var timeoutOne="";
    function getStatesOne(value) {
        $scope.agenttOne = [];
        var newValueOne=value;
        if(newValueOne != oldValueOne){
            if (timeoutOne) $timeout.cancel(timeoutOne);
            timeoutOne = $timeout(
                function(){
                    $http.post('agentInfo/selectAllInfo','item=' + value,
                        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
                        .then(function (response) {
                            if(response.data.length==0) {
                                //$scope.agenttOne.push({value: "", text: "全部"});
                            }else{
                                //$scope.agenttOne.push({value: "", text: "全部"});
                                for(var i=0; i<response.data.length; i++){
                                    $scope.agenttOne.push({value:response.data[i].agentNo,text:response.data[i].agentNo + " " + response.data[i].agentName});
                                }
                            }
                            $scope.oneAgent = $scope.agenttOne;
                            oldValueOne = value;
                        });
                },800);
        }
    };

	//页面绑定回车事件
	$document.bind("keypress", function(event) {
		$scope.$apply(function (){
			if(event.keyCode == 13){
				$scope.selectInfo();
			}
		})
	});

})